/*
 * @Author: ZhaoZhiqi
 * @Date: 2022-08-18 10:03:37
 * @LastEditors: Kevin Zhao
 * @LastEditTime: 2023-05-10 20:35:38
 * @Description: store
 * @FilePath: \tuanfeng-mini\src\store\index.ts
 */
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)

import { getOpenIdAPI } from "../api/login"

const store = new Vuex.Store({
    state: {
        avatar: '',
        nickname: '',
        openId: ''
    },
    mutations: {
        setData(state, payload) {
            console.log(payload)
            state[payload.key] = payload.value;
        },
        checkUserState(state) {
            let openId = wx.getStorageSync('openId');
            let avatar = wx.getStorageSync('avatar');
            let nickname = wx.getStorageSync('nickname');

            if (openId && nickname) {
                state.openId = openId;
                state.avatar = avatar;
                state.nickname = nickname;
            }
        }
    },
    actions: {
        getOpenId({ state, commit, dispatch }, payload) {
            return new Promise((resolve, reject) => {
                wx.login({
                    success(res) {
                        console.log(res)

                        getOpenIdAPI({ code: res.code }).then(res => {
                            console.log(res)

                            commit('setData', { key: "openId", value: res.data.openid });
                            wx.setStorageSync('openId', res.data.openid);
                            resolve(res);
                        })
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            })
        },
        getUserProfile({ state, commit, dispatch }, payload) {
            return new Promise((resolve, reject) => {
                // 获取头像和昵称
                (wx as any).getUserProfile({
                    desc: "用于获取用户头像与昵称",
                    success: (response) => {
                        commit('setData', { key: "avatar", value: response.userInfo.avatarUrl });
                        commit('setData', { key: "nickname", value: response.userInfo.nickName });
                        wx.setStorageSync('avatar', response.userInfo.avatarUrl);
                        wx.setStorageSync('nickname', response.userInfo.nickName);
                        resolve(response);
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            })
        },
    }
})

export default store